package io.gitee.chearnee.fw.datasecurity.core.executor.desensitization;

import io.gitee.chearnee.fw.common.utils.AnnotationUtil;
import io.gitee.chearnee.fw.datasecurity.core.common.SDAnnotationCacheUtil;
import io.gitee.chearnee.fw.datasecurity.core.handler.desensitization.SDRuleHandler;
import io.gitee.chearnee.fw.datasecurity.core.handler.desensitization.SDRuleHandlerFactory;
import org.springframework.core.MethodParameter;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 11/9/2022 5:04 PM
 */

public class StringSDExecutor implements SDExecutor<String> {

    public Object execute(String obj, MethodParameter returnType, Set<Class<?>> disabledClasses) {
        return executeHandler(obj, returnType, disabledClasses);
    }

    private Object executeHandler(Object obj, MethodParameter returnType, Set<Class<?>> disabledClasses) {
        Annotation generalField = AnnotationUtil.checkOneOfAnnotation(returnType, SDAnnotationCacheUtil.getCacheSDAnnotations()).orElse(null);
        return execute(obj.toString(), generalField, disabledClasses);
    }

    /**
     * 字符串脱敏执行器
     *
     * @param obj
     * @param generalField
     * @param disabledClasses
     * @return
     */
    @Override
    public String execute(String obj, Annotation generalField, Set<Class<?>> disabledClasses) {
        if (generalField == null) {
            return obj;
        }
        if (disabledClasses.contains(generalField.annotationType())) {
            return obj;
        }
        SDRuleHandler sdRuleHandler = SDRuleHandlerFactory.getSDRuleHandler(generalField.annotationType());
        return sdRuleHandler.mask(generalField, obj);
    }
}
